// 地图
Ext.define('Health.view.PopMap', {
    extend: 'Ext.Container',
    xtype: 'popmap',


    config: {
        id: "baidumap",
        layout: 'vbox',
        listeners: {
            activate: function () {
                //console.log('activate event popmap.');
                this.initBaidumap();
            }
        },
        items: [
            {
                xtype: 'toolbar',
                docked: 'top',
                items: [
                    {
                        xtype: 'button',
                        text: '返回',
                        handler:gotoFn
                    }
 
                ]
            },
            {
                xtype: 'container',
                id: "popmapdiv",
                html: "正在加载地图...",
                flex: 1
            }
        ], listeners: {
            back:gotoFn
        }
    },

    isMap: false,
    baidumap: null,
    area : '',

    initBaidumap: function () {
        if (!this.isMap && BMap != 'undefined') {
            this.isMap = true;

            console.log(new BMap.Map("popmapdiv"));
            var map = new BMap.Map('popmapdiv');

            map.addControl(new BMap.NavigationControl());
            map.addControl(new BMap.ScaleControl());
            var point = new BMap.Point(108.953451, 34.265773);
            map.centerAndZoom(point, 16);
            this.baidumap = map;

        }
    },
    

    driving: function(lng, lat) {
         Ext.Viewport.mask({
             xtype: 'loadmask',
             message: '加载中...'
         });

         var bmap = this.baidumap;
         var _this = this;

         var onSuccess = function(position) {
             var gpsPoint = new BMap.Point(
                 position.coords.longitude,
                 position.coords.latitude);

             BMap.Convertor.translate(gpsPoint, 0, function(point) {
                 bmap.clearOverlays();
                 var driving = new BMap.DrivingRoute(bmap, {
                     renderOptions: {
                         map: bmap,
                         autoViewport: true
                     }
                 });
                 driving.search(point, new BMap.Point(lng, lat));
                 _this.addControl();
             });
             Ext.Viewport.unmask();
         };

         // onError Callback receives a PositionError object
         //
         var onError = function(error) {
             cordova.exec(function(message) {}, function(error) {}, "Messages", "showMsg", [error.message]);
             Ext.Viewport.unmask();
         }

         navigator.geolocation.getCurrentPosition(onSuccess, onError);
     },
     addControl: function() {
         // 定义一个控件类,即function
         var bmap = this.baidumap;
         var _this = this;

         function ZoomControl() {
             // 默认停靠位置和偏移量
             this.defaultAnchor = BMAP_ANCHOR_TOP_RIGHT;
             this.defaultOffset = new BMap.Size(10, 10);
         }

         // 通过JavaScript的prototype属性继承于BMap.Control
         ZoomControl.prototype = new BMap.Control();

         // 自定义控件必须实现自己的initialize方法,并且将控件的DOM元素返回
         // 在本方法中创建个div元素作为控件的容器,并将其添加到地图容器中
         ZoomControl.prototype.initialize = function(map) {
             // 创建一个DOM元素
             var div = document.createElement("div");
             // 添加文字说明
             div.appendChild(document.createTextNode("退出导航"));
             // 设置样式
             div.style.cursor = "pointer";
             div.style.border = "3px solid #060606";
             div.style.color = '#fff';
             div.style.borderRadius = '5px';
             div.style.padding = "6px";
             // div.class="x-button-normal x-button x-layout-box-item x-stretched"
             div.style.backgroundColor = "#383838";
             // 绑定事件,点击一次放大两级
             div.onclick = function(e) {
                //Ext.Viewport.mask({ xtype: 'loadmask',message: '加载中...' });
                bmap.removeControl(_this.zoomCtrl);
                _this.search();
                
             }
             // 添加DOM元素到地图中
             bmap.getContainer().appendChild(div);
             // 将DOM元素返回
             return div;
         }
         // 创建控件
         this.zoomCtrl = new ZoomControl();
         // 添加到地图当中
         bmap.addControl(this.zoomCtrl);
     },

    search: function (area) {
        if (!this.isMap && BMap != 'undefined') {
            this.initBaidumap();
        }
        console.log("search = " + area);
        Ext.Viewport.mask({
             xtype: 'loadmask',
             message: '加载中...'
         });
        this.area = area;
        
        var baidumap = this.baidumap;
        

        var opts = {
                width: 240,     // 信息窗口宽度
                height: 80,     // 信息窗口高度
                enableMessage:false//设置允许信息窗发送短息  
            };
        var myGeo = new BMap.Geocoder();

        Ext.Viewport.mask({ xtype: 'loadmask', message: '加载数据中...' });
        Ext.Ajax.request({
            url: Global.api_url + '/cloud/1/area_status_info',
            params: {cadid:localGet('cadid')},
            method: 'POST',
            scope: this,
            success: function (response) {
                Ext.Viewport.unmask();
                var returnText = Ext.decode(response.responseText);
                if (returnText.Variables.Result.code == 0) {
                    // 将地址解析结果显示在地图上，并调整地图视野
                 myGeo.getPoint(area, function (point) {
                     if (point) {
                         baidumap.centerAndZoom(point, 16);
                          var marker = new BMap.Marker(point);
                         baidumap.addOverlay(marker);
                         var sContent =
                    "<h4 style='margin:0 0 5px 0;padding:0.2em 0'>"+returnText.Variables.data.name+"</h4>" +
                        "<p style='margin:0;line-height:1.5;font-size:12px;text-indent:2em'>"+returnText.Variables.data.explain.substring(0,30)+"..." +
                        "<a href='javascript:Ext.getCmp(\"baidumap\").driving(" + point.lng + ", " + point.lat + ");void(0)'>导航</a></p>"+
                        "</div>";
                         var infoWindow = new BMap.InfoWindow(sContent, opts);  // 创建信息窗口对象
                         marker.openInfoWindow(infoWindow, point); //开启信息窗口
                         marker.addEventListener("click", function(){this.openInfoWindow(infoWindow);});
                     }
                 }, "西安市");
                    document.getElementById('index_tel').innerText=returnText.Variables.data.tel;
                    document.getElementById('index_address').innerText=returnText.Variables.data.address;
                    Ext.getCmp('area_info').setHtml(returnText.Variables.data.explain);
                }
            },
            failure: function () {//请求失败时执行操作
                Ext.Viewport.unmask();
                cordova.exec(function(message){}, function(error){}, "Messages", "showMsg", ['请求失败,服务器维护中...']);
            }
        });
        Ext.Viewport.unmask();
    }
});